const { db, query } = require("../../db/db");
const {
  createToken,
  createToken_refresh,
} = require("../../jsonwebtoken/index");

async function Login(req, res) {
  console.log(22333, req);
  const UserName = req.body.UserName;
  const PassWord = req.body.PassWord;

  const LoginSql =
    "SELECT PassWord,UserId, \
    IFNULL(UserName,'') as UserName,\
    IFNULL(HeaderImg,'') as HeaderImg \
                  FROM User \
                  WHERE userId=?";

  const Login_res = await query(LoginSql, [UserName]);

  if (Login_res.length > 0) {
    if (PassWord === Login_res[0].PassWord) {
      //密码正确
      res.send({
        status: 0,
        data: {
          accessToken: createToken({
            username: UserName,
          }),
          refreshToken: createToken_refresh({
            username: UserName,
          }),
          username: Login_res[0].UserName,
          HeaderImg: Login_res[0].HeaderImg,
          UserId: Login_res[0].UserId,
          // 一个用户可能有多个角色
        },
      });
    } else {
      res.send({
        status: 1,
        data: {
          message: "密码或账号错误",
        },
      });
    }
  }
}

module.exports = { Login };
